package com.didispace.hystrixCollapser;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
public class HystrixCollapserController {

    @Autowired
    UserService userService;

    // 合并请求测试
    @RequestMapping(value = "/hystrixCollapser", method = RequestMethod.GET)
    public List<User> hystrixCollapser() throws ExecutionException, InterruptedException {

        HystrixRequestContext ctx = HystrixRequestContext.initializeContext();

        List<User> userList = new ArrayList<>();
        Future<User> queue1 = new UserCollapseCommand(userService, 1L).queue();
        Future<User> queue2 = new UserCollapseCommand(userService, 2L).queue();
        Future<User> queue3 = new UserCollapseCommand(userService, 3L).queue();
        User user1 = queue1.get();
        User user2 = queue2.get();
        User user3 = queue3.get();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        ctx.close();
        return userList;

    }

    // 同步请求测试
    @RequestMapping(value = "/syncHystrixCollapser", method = RequestMethod.GET)
    public List<User> syncHystrixCollapser() {

        HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
        List<User> userList = new ArrayList<>();
        User user1 = new UserCollapseCommand(userService, 1L).execute();
        User user2 = new UserCollapseCommand(userService, 2L).execute();
        User user3 = new UserCollapseCommand(userService, 3L).execute();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        ctx.close();
        return userList;
    }
}

// http://localhost:9001/hystrixCollapser
// [
//     {
//     "id": 1,
//     "name": "name01",
//     "age": 21
//     },
//     {
//     "id": 2,
//     "name": "name02",
//     "age": 22
//     },
//     {
//     "id": 3,
//     "name": "name03",
//     "age": 23
//     }
// ]

// http://localhost:9001/syncHystrixCollapser
// [
//     {
//     "id": 1,
//     "name": "name01",
//     "age": 21
//     },
//     {
//     "id": 2,
//     "name": "name02",
//     "age": 22
//     },
//     {
//     "id": 3,
//     "name": "name03",
//     "age": 23
//     }
// ]

// SpringCloud (九) Hystrix请求合并的使用
// https://blog.csdn.net/u012586326/article/details/112343701